import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { StorageService } from '../providers';
import { AppHttpResponse } from '../providers/interface';

interface AppHeaders {
  [name: string]: string | string[];
}

@Injectable()
export class AppInterceptor implements HttpInterceptor {
  constructor(
    private router: Router,
    private storage: StorageService,
    private notification: NzNotificationService
  ) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    // 自定义 HttpHeaders
    const headers: AppHeaders = {};
    const token = this.storage.get('access_token');
    if (token) {
      headers.Authorization = token;
    }
    // 克隆请求，并发送
    const newRequest = request.clone({
      setHeaders: headers,
    });
    return next.handle(newRequest).pipe(
      tap({
        next: (event) => {
          if (event instanceof HttpResponse) {
            const result: AppHttpResponse<any> = event.body;
            if (result.success === false) {
              this.notification.error('错误提示', result.message);
            }
          }
        },
        error: (error: HttpErrorResponse) => {
          this.notification.error('错误提示', '网络请求失败');
        },
      })
    );
  }

  /**
   * 401 状态下，退出登录
   */
  logout(): void {
    this.storage.clear();
    this.router.navigateByUrl('/auth/login');
  }
}
